//
//  AddFirendViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "AddFirendViewController.h"
#import "FKSearchBar.h"
#import "AddSearchFirendCell.h"
#import "MyFirendData.h"
#import "FirendDetailViewController.h"
#import "NearMenViewController.h"
#import "MyFirendHeaderView.h"
#import "AddSearchBarCell.h"
@interface AddFirendViewController ()<UITableViewDelegate,UITableViewDataSource,FKSearchBarDelegate>
{
    FKSearchBar * illSeachBar;
}

@property (nonatomic, strong) NSString *firendCountStr;
@property (nonatomic, assign) BOOL isSearch;

/**
 *  搜索页数
 */
@property (nonatomic, assign) NSInteger firendPage;
/**
 *  搜索的字
 */
@property (nonatomic, strong) NSString *searchFirends;
/**
 *  搜索获取的数据存放的数组
 */
@property (nonatomic, strong) NSMutableArray *searchFirendsArray;
@property (strong, nonatomic) IBOutlet UITableView *addFirendTableView;

@end

@implementation AddFirendViewController
- (NSMutableArray *)searchFirendsArray{
    if (_searchFirendsArray == nil) {
        self.searchFirendsArray = [NSMutableArray array];
    }
    return _searchFirendsArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.addFirendTableView.delegate = self;
    self.addFirendTableView.dataSource = self;
    [self setNaviBarAttribute];
    self.navigationItem.title = @"搜索好友";
    self.addFirendTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    // Do any additional setup after loading the view from its nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView的代理方法 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else
    return self.searchFirendsArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    view.backgroundColor = [UIColor colorWithRed:221/ 255.0 green:221/255.0 blue:221/255.0 alpha:1];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (kScreenWidth == 414) {
            return 97;
        }else{
            return 88;
        }
    }else{
        if (kScreenWidth == 414) {
            return 54;
        }else{
            return 44;
            
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        if (self.searchFirendsArray.count > 0) {
           return 20;
        }else{
            return 0;
        }
    }else{
        return 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        if (self.searchFirendsArray.count > 0) {
            MyFirendHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendHeaderView" owner:self options:nil] lastObject];
            headerView.initialLabel.hidden = YES;
            headerView.backgroundColor = [UIColor colorWithRed:237.0/255 green:237.0/255 blue:237.0/255 alpha:1];
            return headerView;
        }
//        headerView.footView.frame = CGRectMake(0, 19.75, kScreenWidth, 0.25);
//        headerView.footView.backgroundColor = [UIColor colorWithRed:204/ 255.0 green:204/255.0 blue:204/255.0 alpha:1];
        return  nil;
    }
    else return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddSearchFirendCell *searchcell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    AddSearchBarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddSearchBarCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddSearchBarCell" owner:self options:nil] firstObject];
        }
    }
    if (!searchcell) {
        if (kScreenWidth == 414) {
            searchcell = [[[NSBundle mainBundle] loadNibNamed:@"AddSearchFirendCell" owner:self options:nil] lastObject];
        }else{
            searchcell = [[[NSBundle mainBundle] loadNibNamed:@"AddSearchFirendCell" owner:self options:nil] firstObject];
        }
    }
    if (indexPath.section == 0) {
        illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        illSeachBar.fkSearchRequestDelegate = self;illSeachBar.searchTextField.text = self.searchFirends;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.contentView addSubview: illSeachBar];
        [cell.nearMButton addTarget:self action:@selector(jumpNearView) forControlEvents:UIControlEventTouchUpInside];
        cell.nearMButton.backgroundColor = [UIColor clearColor];
        return cell;
    }else{
        MyFirendData *firendData = [[MyFirendData alloc] init];
        firendData = [self.searchFirendsArray objectAtIndex:indexPath.row];
        [searchcell.headerImageView setImageWithURL:[NSURL URLWithString:firendData.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
        searchcell.headerImageView.layer.masksToBounds = YES;
        searchcell.headerImageView.layer.cornerRadius = 2;
        searchcell.nameLabel.text = firendData.username;
        return searchcell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        FirendDetailViewController *detailVC = [[FirendDetailViewController alloc] init];
        MyFirendData *firendData = [[MyFirendData alloc] init];
        firendData = [self.searchFirendsArray objectAtIndex:indexPath.row];
        detailVC.firendId = firendData.uid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)jumpNearView{
    NearMenViewController *nearMenVC = [[NearMenViewController alloc] init];
            [self.navigationController pushViewController:nearMenVC animated:YES];
}


#pragma mark - 搜索框的执行方法 -
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    [self.searchFirendsArray removeAllObjects];
    illSeachBar.searchTextField.text = voice;
    self.isSearch = YES;
    self.firendPage = 1;
    self.searchFirends = voice;
    [self.addFirendTableView addFooterWithTarget:self action:@selector(loadDatad)];
    [self loadDatad];
}
- (void)SearchString
{
    [self.searchFirendsArray removeAllObjects];
    [illSeachBar.searchTextField resignFirstResponder];
    self.isSearch = YES;
    self.firendPage = 1;
    MyNSLog("搜索");
    self.searchFirends = illSeachBar.searchTextField.text;
    [self.addFirendTableView addFooterWithTarget:self action:@selector(loadDatad)];
    [self loadDatad];
    
}

- (void)loadDatad{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    if ([self.searchFirends length] == 0){
        
    }else{
        [dict setObject:self.searchFirends forKey:@"keyword"];
    }
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",self.firendPage] forKey:@"page"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@user/search/",kBaseURL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self.addFirendTableView footerEndRefreshing];
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
//            if (self.isSearch == YES){
//                if ([self.searchFirendsArray count] != 0){
//                    [self.searchFirendsArray removeAllObjects];
//                }
//            }
            if (jsonDictArr != nil) {
                self.firendPage++;
                MyNSLog("%d", self.firendPage);
                for (NSDictionary * dic in jsonDictArr){
                    MyFirendData *myFirendObjc = [[MyFirendData alloc] init];
                    [myFirendObjc setValuesForKeysWithDictionary:dic];
                    //  单例对数据操作
                    [self.searchFirendsArray addObject:myFirendObjc];
                    MyNSLog("%@", myFirendObjc.uid);
                }
                [self.addFirendTableView reloadData];
            }else if ([jsonDictArr count] < 20){
                [self.addFirendTableView footerEndRefreshing];
            }else{
                if (self.firendPage>1) {
                    MyNSLog("下拉无数据");
                }
            }
        }
        [self.addFirendTableView footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.addFirendTableView footerEndRefreshing];
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
